<template>
  <departmentBase>
    <template v-slot:main-left>
      <SearchTrees
        :inputShow="inputShow"
        :treeData="orgDeptList"
        :defaultProps="defaultProps"
        :lazy="lazy"
        :sysOrgName.sync="sysOrgName"
        @getlazyLoad="lazyLoad"
        @handleNodeClickTree="handleNodeClickTree"
      />
    </template>
    <template v-slot:search-info>
      <searchMain
        size="mini"
        ref="searchMain"
        :model="formData"
        :itemList="formItemList"
        :searchBtn="searchBtn"
      />
    </template>
    <template v-slot:table-main>
      <common-table
        :data="infoList"
        border
        :columns-item="columns"
        :loading="false"
        :seqColumns="seqColumns"
        :displayColumn="displayColumn"
        :page.sync="page"
        @changePage="changePage"
        @removeRowData="removeRowData"
        @setDialogBtn="setDialogBtn"
        @handlerEdit="handlerEdit"
      />
    </template>
    <template v-slot:add-dialog>
      <setDialog :flagVisibleSet.sync="dialogShowSet" ref="setDialog" />
    </template>
    <template v-slot:edit-dialog>
      <addDialog
        :dialogVisibleShow.sync="addDialogShow"
        ref="addDialog"
        :selectedDept="selectedDept"
        :organizationId="organizationId"
        @refreshMedicialStaff="refreshMedicialStaff"
      />
    </template>
  </departmentBase>
</template>

<script>
import departmentBase from "@/components/Layout/departmentBase.vue"
import SearchTrees from "@/components/Trees/SearchTrees.vue"
import searchMain from "@/components/CommonForm/form-item/DepartmentForm.vue"
import CommonTable from "@/components/CommonTable/index.vue"
import setDialog from "./dialog/setDialog.vue"
import addDialog from "./dialog/addDialog.vue"
import {
  getOrgAndDescendant,
  getMedicalStaffByPage,
  deleteMedicalStaff,
  getOrgAndDeptLazyLoad,
  getDeptsBySysOrgId,
  saveStaffRegAndDeptBatch,
  getMedicalStaffReg,
  getCurrentSysOrg,
  getChildDeptByHisDeptId,
  getLeafOrganization,
  getStaffOfNotLeafOrg,
  getRegisterType,
  getAdminiDeptsBySysOrgId
} from "@/api/setup/doctors-setup.js"
import {
  ghlbCode,
  departmentType,
  deptCategory,
  departmentType2,
  deptCategory2
} from "@/api/setup/medicalstaff.js"
import success from "@/utils/operation-message.js"
export default {
  components: {
    departmentBase,
    SearchTrees,
    searchMain,
    CommonTable,
    setDialog,
    addDialog
  },
  data() {
    return {
      // 配置表单按钮
      searchBtn: [
        {
          label: "搜索",
          icon: "el-icon-search",
          type: "primary",
          disabled: false,
          handle: () => this.searchStaff()
        },
        {
          label: "新增",
          icon: "el-icon-circle-plus-outline",
          type: "primary",
          disabled: false,
          handle: () => this.handleAddStaff()
        }
      ],
      // 配置是否默认加载假数据
      lazy: true,
      sysOrgName: "", // 树过滤字段
      // 树的数据
      treeData: [
        {
          id: "1001",
          label: "潜江市卫生健康委员会",
          children: [
            {
              id: "1001001",
              label: "潜江市龙湾镇卫生院"
            }
          ]
        }
      ],
      // 配置input框是否显示
      inputShow: true,
      organizationId: "", // 权限
      formData: {
        nameOrPhone: ""
      },
      defaultProps: {
        id: "id",
        label: "name",
        children: "hasChildren",
        isLeaf: "isLeaf"
      },
      onclickOrgId: null, // 搜索表格条件
      onclickDeptId: null,
      selectedDept: null,
      orgDeptList: [], // 加载树条件
      // 医护人员表点击岗位设置，将该医护人员信息保存到staffRow
      staffRow: undefined,
      formItemList: [
        {
          type: "Input",
          label: "",
          prop: "nameOrPhone",
          span: 6,
          placeholder: "姓名、工号或电话"
        }
      ],
      infoList: [],
      // 配置展开列的序号显示
      seqColumns: {
        seq: false,
        checkbox: false
      },
      // 配置显示的label标签
      columns: [
        { prop: "name", label: "姓名", width: "100" },
        { prop: "staffCode", label: "工号", width: "100" },
        { prop: "userName", label: "登录账号", width: "150" },
        { prop: "professinalName", label: "职称", width: "100" },
        { prop: "deptName", label: "科室", width: "100" },
        { prop: "telephone", label: "联系电话", width: "150" }
      ],
      // 控制表格操作按钮的显示隐藏
      displayColumn: {
        operationCol: true,
        editBtn: true,
        removeBtn: true,
        setBtn: true,
        diagnoseBtn: true
      },
      // 弹框控制
      dialogShowSet: false,
      addDialogShow: false, // 新增弹框
      // 分页
      page: {
        curPage: 1,
        limit: 10,
        total: 0
      },
      staff: null,
      parentId: "", // 上级机构id
      sysOrganId: "", // 机构id
      userInfo: JSON.parse(window.sessionStorage.getItem("userInfo")),
      // 模拟数据
      // userInfo: {
      //   sysOrganizationId: "1001"
      // },
      sysOrgId: ""
    }
  },
  created() {
    this.organizationId = this.userInfo.sysOrganizationId
  },
  methods: {
    // 懒加载
    async lazyLoad(node, resolve) {
      console.log(node)
      if (node.level == 0) {
        const res = await getCurrentSysOrg(this.organizationId)
        console.log(res)
        if (res.code === "1000") {
          let orgInfo = res.data[0]
          this.orgDeptList = [
            {
              name: orgInfo.name,
              id: orgInfo.sysOrganizationId,
              isLeaf: orgInfo.isLeaf,
              type: "org",
              maxChildId: orgInfo.maxChildId
            }
          ]
        }
      } else {
        // 节点为机构
        if (node.data.type == "org") {
          this.sysOrganId = node.data.id
          if (node.data.maxChildId === null) {
            // 节点为科室
            this.parentId = "-1"
            let params = {
              hisDeptId: node.data.id,
              sysOrganizationId: this.parentId
            }
            const resC = await getDeptsBySysOrgId(params)
            resC.data.forEach(item => {
              item.name = item.label
            })
            if (resC.code === "1000") {
              resolve(resC.data)
            }
          } else {
            const resA = await getOrgAndDeptLazyLoad(node.data.id)
            // console.log(resA)
            if (resA.code === "1000") {
              resA.data.forEach(item => {
                item.name = item.label
              })
              // console.log(resA.data)
              resolve(resA.data)
            }
          }
        } else {
          // 节点为科室
          // console.log(this.sysOrganId)
          let params = {
            hisDeptId: node.data.id,
            sysOrganizationId: this.sysOrganId
          }
          const resC = await getDeptsBySysOrgId(params)
          resC.data.forEach(item => {
            item.name = item.label
          })
          if (resC.code === "1000") {
            resolve(resC.data)
          }
        }
      }
    },
    // 过滤树字段

    // 搜索按钮
    searchStaff() {
      this.page.curPage = 1
      this.getMedicalStaffs()
    },
    // 监听分页数据
    changePage(curPage, limit) {
      this.page.curPage = curPage
      this.page.limit = limit
      this.getMedicalStaffs()
    },
    // 获取表格列表
    async getMedicalStaffs() {
      let listQuery = {
        orgId: this.onclickOrgId, // 机构ID
        deptId: this.onclickDeptId, // 科室Id
        nameOrPhone: this.formData.nameOrPhone, // 查询关键字
        curPage: this.page.curPage,
        limit: this.page.limit
      }
      // console.log(listQuery)
      // 医护人员列表
      const res = await getStaffOfNotLeafOrg(listQuery)
      if (res.code === "1000") {
        let staffs = res.data.records
        this.infoList = staffs.map((item, index, arr) => {
          item.eSignature = item.elecSignature
          return item
        })
        // console.log(this.infoList)
        this.page.total = res.data.total
      }
    },
    // 监听左侧树的点击数据
    handleNodeClickTree(data) {
      this.page.curPage = 1
      if ("dept" == data.type) {
        this.selectedDept = data
        this.onclickDeptId = data.id
        // 获取选中机构的挂号类别options
        this.getRegisterList(data.sysOrganizationId)
      } else {
        this.onclickOrgId = data.id // 机构id
        this.selectedDept = null
        this.onclickDeptId = "" // 科室id
        // 获取选中机构的挂号类别options
        this.getRegisterList(this.onclickOrgId)
      }
    },
    getRegisterList(oragnId) {
      this.onclickOrgId = oragnId
      this.getMedicalStaffs()
    },
    // 点击删除按钮
    removeRowData(row) {
      console.log()
      this.$confirm("此操作将删除该医护人员，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteMedicalStaff(row.row.hisMedicalStaffId).then(res => {
            if (res.code === "1000") {
              this.getMedicalStaffs()
              this.$message({
                message: res.msg,
                type: "success",
                duration: 2000
              })
            } else {
              this.$message({
                message: res.msg,
                type: "error",
                duration: 2000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
            duration: 2000
          })
        })
    },
    // 刷新列表
    refreshMedicialStaff() {
      this.getMedicalStaffs()
    },
    // 监听岗位设置按钮弹框
    setDialogBtn(data) {
      this.dialogShowSet = true // 弹框显示
      this.staffRow = data.row // 医护信息
      this.$nextTick(() => {
        this.$refs.setDialog.init(data.row)
      })
    },
    // 点击新增按钮
    handleAddStaff() {
      this.addDialogShow = true
      this.$nextTick(() => {
        this.$refs.addDialog.init()
      })
    },
    // 点击表格修改
    handlerEdit(scope) {
      console.log(scope)
      this.addDialogShow = true
      let roleId = []
      if (scope.row.roleId && typeof scope.row.roleId === "string") {
        roleId = scope.row.roleId.split(",")
        scope.row.roleIdArr = roleId
      } else {
        scope.row.roleIdArr = []
      }
      this.staff = Object.assign({}, scope.row)
      this.$nextTick(() => {
        this.$refs.addDialog.handleUpdateStaff(this.staff)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .table-item {
  height: 100%;
  margin-right: 0 !important;
}
</style>
